package OT.shoufouni.gpsMaps;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.andnav.osm.util.GeoPoint;
import org.andnav.osm.views.OpenStreetMapView;
import org.andnav.osm.views.OpenStreetMapView.OpenStreetMapViewProjection;
import org.andnav.osm.views.overlay.OpenStreetMapViewItemizedOverlay;
import org.andnav.osm.views.overlay.OpenStreetMapViewOverlayItem;

import OT.shoufouni.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.Log;

public class routeLocation extends
        OpenStreetMapViewItemizedOverlay<OpenStreetMapViewOverlayItem> {

    private final static double E6 = 1000000;
	protected static final StringBuilder description = new StringBuilder("");

    public routeLocation(Context ctx,List<OpenStreetMapViewOverlayItem> aList,OnItemTapListener<OpenStreetMapViewOverlayItem> aOnItemTapListener ) {
        super (ctx, aList, ctx.getResources().getDrawable(
        		R.drawable.bullet_red), new Point(8, 8), aOnItemTapListener, null);
    }

    public static routeLocation getInstance(final Context ctx,OpenStreetMapView osmv, 
    		GeoPoint from, GeoPoint to) {
        ArrayList<OpenStreetMapViewOverlayItem> route = new 
        ArrayList<OpenStreetMapViewOverlayItem>();

        try {
        	// conect to get the route
            URL url = new URL( "http://www.yournavigation.org/api/1.0/gosmore.php?flat="
                            + from.getLatitudeE6() / E6 + "&flon="
                            + from.getLongitudeE6() / E6 + "&tlat="
                            + to.getLatitudeE6() / E6 + "&tlon="
                            + to.getLongitudeE6() / E6+"&instructions=1");
            Log.i("URL", url.toString());
            
            // play with ip, suppose to help connect to the url afterwards
            try {
                InetAddress i = InetAddress.getByName(url.toString());
              } catch (UnknownHostException e) {
            	  Log.e("ip", e.getMessage());
              }

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(url.openStream()));

            String line;
            double lon = 0, lat = 0;
            boolean readCoordinates = false;
            boolean readDescription = false;
            Boolean firstReadDesc = true;
            int counter = 1;
            
            Log.d("URL", "reading cordinates");
            
            while ((line = reader.readLine()) != null) {
            	if ((firstReadDesc)&&(line.trim().startsWith("<description>"))) {
            		Log.d("readDescription", line);
                    line = line.substring(line.indexOf(">") + 1).trim();
                    readDescription = true;
                    firstReadDesc = false;
                }
            	else if (line.trim().contains("</description>")) {
            		readDescription = false;
            		Log.d("stop readDescription", line);
                }
            	
            	else if (line.trim().startsWith("<coordinates>")) {
            		Log.d("readCoordinates", line);
                    line = line.substring(line.indexOf(">") + 1).trim();
                    readCoordinates = true;
                    
                }
            	else if (line.trim().startsWith("</coordinates>")) {
                    readCoordinates = false;
                    Log.d("stop readCoordinates", line);
                }
                if (readDescription) {   
                	Log.d("description", line);
                	description.append(line.substring(0, line.lastIndexOf("&lt"))+"\n");
                }
                else if (readCoordinates) {      	
                    lon = Double.parseDouble(line.substring(0, line
                            .indexOf(',')));

                    line = line.substring(line.indexOf(',') + 1);

                    lat = Double.parseDouble(line);

                    route.add(new OpenStreetMapViewOverlayItem("n "+counter++,
                            "point", new GeoPoint(lat, lon)));
                }
            }
            reader.close();
            Log.d("desc", description.toString());

        } catch (Exception e) {
        	Log.e("routeLocation", e.getMessage());
            return null;
        }
        
        OnItemTapListener<OpenStreetMapViewOverlayItem> aOnItemTapListener 
        = new OnItemTapListener<OpenStreetMapViewOverlayItem>(){
        	@Override
	        public boolean onItemTap(int index, OpenStreetMapViewOverlayItem item) {
        		final double x = (double)item.mGeoPoint.getLatitudeE6()/1000000;
	            final double y = (double)item.mGeoPoint.getLongitudeE6()/1000000;
	            final String title = item.mTitle;
	            final String descrpt = item.mDescription;
	            new AlertDialog.Builder(ctx)
	            .setMessage(description.toString())
	            .setTitle("Directions:\nCurrent location "+descrpt+" "+title)
	            .setNegativeButton("ok", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    dialog.cancel();
	               }
	               })
	             .show();       
	        	return true; // We 'handled' this event.
	        }	
        };

        return new routeLocation(ctx, route,aOnItemTapListener);
    }

    public void onDraw(final Canvas c, final OpenStreetMapView mapView) {
        OpenStreetMapViewProjection pj = mapView.getProjection();

        // create the route
        
        Point from = new Point();
        Point to = new Point();

        Paint paint = new Paint();
        //paint.setColor(Color.RED);
        paint.setColor(Color.rgb(0, 0, 255));
        paint.setStrokeWidth(5);
        paint.setAlpha(100);

        for (int i = 0; i < mItemList.size(); i++) {
            pj.toMapPixels(mItemList.get(i).mGeoPoint, from);

            if (i > 0) {
                pj.toMapPixels(mItemList.get(i - 1).mGeoPoint, to);

                c.drawLine(from.x, from.y, to.x, to.y, paint);
            }

            onDrawItem(c, i, from);
        }
    }
}
